import 'package:auto_route/auto_route.dart';
import 'package:casdon/common/widget/common_app_bar.dart';
import 'package:casdon/common/widget/common_loading_widget.dart';
import 'package:casdon/modules/me/application/notification/service_channel_list_notifier.dart';
import 'package:casdon/modules/me/data/api/service_channel_list_api.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

@RoutePage()
class ServiceChannelListScreen extends ConsumerStatefulWidget {
  const ServiceChannelListScreen({super.key});

  @override
  ConsumerState<ServiceChannelListScreen> createState() =>
      _PurchaseChannelScreenState();
}

class _PurchaseChannelScreenState
    extends ConsumerState<ServiceChannelListScreen> {
  final TextEditingController _searchController = TextEditingController();
  final FocusNode _searchFocusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    _searchController.addListener(_onSearchChanged);
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadInitialData();
    });
  }

  void _loadInitialData() {
    final notifier = ref.read(serviceChannelListProvider.notifier);
    notifier.fetchData();
  }

  void _onSearchChanged() {
    ref
        .read(serviceChannelListProvider.notifier)
        .search(_searchController.text);
  }

  @override
  void dispose() {
    _searchController.dispose();
    _searchFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    final state = ref.watch(serviceChannelListProvider);

    return Scaffold(
      backgroundColor: Colors.white,
      appBar: CommonAppBar(title: "购买渠道"),
      body: SafeArea(
        child: Column(
          children: [
            // ✅ 搜索栏（完全匹配图片样式）
            _buildSearchBar(state.value ?? []),
            state.when(
              loading: () =>
                  Expanded(child: Center(child: const CommonLoadingWidget())),
              error: (error, stack) =>
                  Expanded(child: Center(child: Text('加载失败'))),
              data: (state) => Expanded(child: _buildChannelList(state)),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildSearchBar(List<ServiceChannel> state) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      padding: const EdgeInsets.symmetric(horizontal: 12),
      height: 36,
      decoration: BoxDecoration(
        color: Colors.grey.shade100, // ✅ 浅灰色背景
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Icon(Icons.search, size: 20, color: Colors.grey.shade500),
          const SizedBox(width: 8),
          Expanded(
            child: TextField(
              controller: _searchController,
              focusNode: _searchFocusNode,
              decoration: InputDecoration(
                hintText: '搜索渠道名称',
                hintStyle: TextStyle(color: Colors.grey.shade500),
                border: InputBorder.none,
                isDense: true,
              ),
              style: const TextStyle(fontSize: 14),
            ),
          ),
          if (state.isNotEmpty)
            IconButton(
              icon: Icon(Icons.clear, size: 18, color: Colors.grey.shade500),
              onPressed: () {
                _searchController.clear();
              },
            ),
        ],
      ),
    );
  }

  // ✅ 渠道列表
  Widget _buildChannelList(List<ServiceChannel> state) {
    if (state.isEmpty) {
      return Center(
        child: Text('未找到相关渠道', style: TextStyle(color: Colors.grey.shade600)),
      );
    }

    return ListView.builder(
      itemCount: state.length,
      itemBuilder: (context, index) {
        final channel = state[index];
        return _buildChannelItem(channel);
      },
    );
  }

  // ✅ 单个渠道项
  Widget _buildChannelItem(ServiceChannel channel) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(color: Colors.grey.shade200, width: 0.5),
        ),
      ),
      child: ListTile(
        contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 0),
        minVerticalPadding: 0,
        title: Text(
          channel.name.trim(),
          style: const TextStyle(fontSize: 16, color: Colors.black87),
        ),
        onTap: () {
          _onChannelSelected(channel);
        },
      ),
    );
  }

  void _onChannelSelected(ServiceChannel channel) {
    context.router.maybePop(channel);
  }
}
